// pages/home/home.js
Page({
  goToSearch() {
    wx.navigateTo({
      url: '/packageA/pages/search/search',
    })
  },
  getTitles() {
    wx.request({
      url: 'http://localhost:3000/titles',
      success: (resp) => {
        this.setData({
          titles: resp.data
        })
      }
    })
  },
  changeUid(e) {
    const uid = e.target.dataset.uid;
    this.setData({
      // 修改id
      uid: uid,
      // 清空原来数据
      list: [],
      // 页码
      pageCode: 1,
    })
    this.getListByUid()
  },
  getListByUid(callback) {
    wx.showLoading({
      title: '数据加载中...',
    })
    const { uid, pageCode, list } = this.data;
    wx.request({
      url: 'http://localhost:3000/list',
      data: {
        uid: uid,
        _page: pageCode
      },
      success: resp => {
        console.log(resp.data)
        this.setData({
          list: list.concat(resp.data),
          totalCount: resp.header['X-Total-Count']
        })
      },
      complete: () => {
        callback && callback();
        wx.hideLoading()
      }
    })
  },
  /**
   * 页面的初始数据
   */
  data: {
    "banners": [
      "../../images/banner1.webp",
      "../../images/banner2.webp",
      "../../images/banner3.webp",
      "../../images/banner4.webp",
    ],
    "titles": [],
    "uid": 1,
    "list": [],
    "pageCode": 1,
    "totalCount": 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getTitles();
    this.getListByUid()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      pageCode: 1,
      list: [],
    })
    this.getListByUid(() => wx.stopPullDownRefresh());
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    const { pageCode, totalCount, list } = this.data;

    // 边界处理
    if(list.length >= totalCount) {

      return ;
    }
    this.setData({
      pageCode: pageCode + 1
    });
    this.getListByUid()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})